package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.TaxListbeanAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.TaxListBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.wangchenlong.datescroller.widget.DateScrollerDialog;
import org.wangchenlong.datescroller.widget.data.Type;
import org.wangchenlong.datescroller.widget.listener.OnDateSetListener;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class TaxlistActivity extends SwipeBackActivity implements View.OnClickListener,ListViewPlus.ListViewPlusListener {
    private String TAG="TaxlistActivity";
    private int taclistCode;
    private ImageView time_right,examine_right;
    private LinearLayout mImageView;

    private TextView showCompanyName,findaddlist;
    private boolean show_button=true;

    private LinearLayout time_lookup,to_examine_lookup;
    private TextView showTime,showCher;
    private ListViewPlus mListView;
    private TaxListBean mTaxListBean;
    private TaxListbeanAdapter mTaxListbeanAdapter;
    private List<TaxListBean>  ListBean = new ArrayList<>();
    private Button quanbu,tongguo,shenghe,weitongguo;

    private String myTime;
    private int my_check_res;


    private static final long HUNDRED_YEARS = 100L * 365 * 1000 * 60 * 60 * 24L;
    private long mLastTime = System.currentTimeMillis();
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM", Locale.ENGLISH);
    private LinearLayout linearLayout,linearLayout_animation;

    private int page_count,count,page_index,stair_count;
    @Override
    public void onRefresh() {

        ListBean.clear();
        intView();
        mTaxListbeanAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if(page_index<page_count){

            loadData(ListViewPlus.LOAD);
        }else{
            Toast.makeText(getBaseContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:

                    //intView();
                    onLoadComplete();
                    Toast.makeText(getBaseContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    loadMode(myTime,my_check_res,page_index);
                    break;
            }

        };
    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }
    private void loadMode(String myTime,int my_check_res,int page_index) {
        Intent intent = getIntent();
        String taxNo = intent.getStringExtra("taxNo");
        String compenyName = intent.getStringExtra("compenyName");
        showCompanyName.setText(compenyName);

        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/hjs_api/Invoice/query_invoice");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("time", myTime);
        params.addBodyParameter("check_res", my_check_res);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("taxNo", taxNo);
        params.addBodyParameter("page_size", 10);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    taclistCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String id = value.getString("id");
                        String uid = value.getString("uid");
                        String taxAmount = value.getString("taxAmount");
                        String ctime = value.getString("ctime");
                        String check_res = value.getString("check_res");
                        mTaxListBean = new TaxListBean(id,uid,taxAmount,ctime,check_res);
                        ListBean.add(mTaxListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (taclistCode == 200) {
                    mTaxListbeanAdapter.notifyDataSetChanged();

                }
                if (taclistCode == 201) {


                }
                if (taclistCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                onLoadComplete();
            }
        });

    }

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taxlist);
        setStatusBar();
        mImageView= (LinearLayout) findViewById(R.id.tax_list_back);
        showCompanyName= (TextView) findViewById(R.id.tax_list_companyName);
        time_lookup= (LinearLayout) findViewById(R.id.tax_time_lookup);
        to_examine_lookup= (LinearLayout) findViewById(R.id.tax_list_to_examine_lookup);
        time_right= (ImageView) findViewById(R.id.taxlist_time_right);
        examine_right= (ImageView) findViewById(R.id.examine_lookup_right);
        findaddlist= (TextView) findViewById(R.id.find_addlist);
        linearLayout = (LinearLayout) findViewById(R.id.examine_button);
       // linearLayout_animation=findViewById(R.id.examine_Animation);
        showTime= (TextView) findViewById(R.id.show_taxTime);
        showCher= (TextView) findViewById(R.id.show_taxCher);
        quanbu= (Button) findViewById(R.id.button_all);
        tongguo= (Button) findViewById(R.id.button_pass);
        shenghe= (Button) findViewById(R.id.button_doexamine);
        weitongguo= (Button) findViewById(R.id.button_notpass);


        mImageView.setOnClickListener(this);
        time_lookup.setOnClickListener(this);
        to_examine_lookup.setOnClickListener(this);
    //    linearLayout_animation.setOnClickListener(this);

        quanbu.setOnClickListener(this);
        tongguo.setOnClickListener(this);
        shenghe.setOnClickListener(this);
        weitongguo.setOnClickListener(this);
        findaddlist.setOnClickListener(this);
        mListView= (ListViewPlus) findViewById(R.id.show_tax_List);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);



        intView();

    }
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.find_addlist:
                finlist();
                break;
            case R.id.tax_list_back:
                finish();
                break;
            case R.id.tax_time_lookup:
                shoewtime();
                linearLayout.setVisibility(View.GONE);
                break;
            case R.id.tax_list_to_examine_lookup:
                if (show_button==true){
                    examine_right.setImageResource(R.drawable.up_show);
                    linearLayout.setVisibility(View.VISIBLE);
                    show_button=false;
                }else {
                    examine_right.setImageResource(R.drawable.xiala);
                    linearLayout.setVisibility(View.GONE);
                    show_button=true;
                }
                break;
            case R.id.button_all:
                my_check_res=0;
                showCher.setText("全部");
                quanbu.setBackgroundResource(R.drawable.begin_textview_shape_change);
                quanbu.setTextColor(Color.WHITE);
                tongguo.setBackgroundResource(R.drawable.list_button);
                tongguo.setTextColor(Color.BLACK);
                shenghe.setBackgroundResource(R.drawable.list_button);
                shenghe.setTextColor(Color.BLACK);
                weitongguo.setBackgroundResource(R.drawable.list_button);
                weitongguo.setTextColor(Color.BLACK);
                 break;
            case R.id.button_pass:
                showCher.setText("通过");
                my_check_res=2;
                tongguo.setBackgroundResource(R.drawable.begin_textview_shape_change);
                tongguo.setTextColor(Color.WHITE);

                quanbu.setBackgroundResource(R.drawable.list_button);
                quanbu.setTextColor(Color.BLACK);
                shenghe.setBackgroundResource(R.drawable.list_button);
                shenghe.setTextColor(Color.BLACK);
                weitongguo.setBackgroundResource(R.drawable.list_button);
                weitongguo.setTextColor(Color.BLACK);
                 break;
            case R.id.button_doexamine:
                showCher.setText("审核中");
                my_check_res=1;
                shenghe.setBackgroundResource(R.drawable.begin_textview_shape_change);
                shenghe.setTextColor(Color.WHITE);

                quanbu.setBackgroundResource(R.drawable.list_button);
                quanbu.setTextColor(Color.BLACK);
                weitongguo.setBackgroundResource(R.drawable.list_button);
                weitongguo.setTextColor(Color.BLACK);
                tongguo.setBackgroundResource(R.drawable.list_button);
                tongguo.setTextColor(Color.BLACK);
                 break;
            case R.id.button_notpass:
                showCher.setText("未通过");
                my_check_res=3;
                weitongguo.setBackgroundResource(R.drawable.begin_textview_shape_change);
                weitongguo.setTextColor(Color.WHITE);

                quanbu.setBackgroundResource(R.drawable.list_button);
                quanbu.setTextColor(Color.BLACK);
                tongguo.setBackgroundResource(R.drawable.list_button);
                tongguo.setTextColor(Color.BLACK);
                shenghe.setBackgroundResource(R.drawable.list_button);
                shenghe.setTextColor(Color.BLACK);
                 break;


        }

    }

    private void finlist() {
        ListBean.clear();
        Intent intent = getIntent();
        String taxNo = intent.getStringExtra("taxNo");
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/hjs_api/Invoice/query_invoice");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("taxNo", taxNo);
        params.addBodyParameter("check_res", my_check_res);
        params.addBodyParameter("time", myTime);
        params.addBodyParameter("page_size", 10);
        Log.e(TAG,  "check_res" + my_check_res+"    myTime"+myTime);

        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    taclistCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                           count= jsonObjec.optInt("count", 0);
                           page_count= jsonObjec.optInt("page_count", 0);
                           page_index= jsonObjec.optInt("page_index", 0);
                        Log.e(TAG, "count:"+count+"  page_count:"+page_count+"  page_index:"+page_index );
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String id = value.getString("id");
                        String uid = value.getString("uid");
                        String taxAmount = value.getString("taxAmount");
                        String ctime = value.getString("ctime");
                        String check_res = value.getString("check_res");
                        mTaxListBean = new TaxListBean(id,uid,taxAmount,ctime,check_res);
                        ListBean.add(mTaxListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (taclistCode == 200) {
                    mTaxListbeanAdapter = new TaxListbeanAdapter(getBaseContext().getApplicationContext(),ListBean);
                    mTaxListbeanAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mTaxListbeanAdapter);

                }
                if (taclistCode == 201) {


                }
                if (taclistCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
               int i=ListBean.size();
               if(i==0){
                   Toast.makeText(getBaseContext().getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
               }else{
                   Toast.makeText(getBaseContext().getApplicationContext(), "已显示查询结果", Toast.LENGTH_SHORT).show();
                   examine_right.setImageResource(R.drawable.xiala);
                   linearLayout.setVisibility(View.GONE);
                   show_button=true;
               }
            }
        });

    }

    private void intView() {
        Intent intent = getIntent();
        String taxNo = intent.getStringExtra("taxNo");
        String compenyName = intent.getStringExtra("compenyName");
        showCompanyName.setText(compenyName);

        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/hjs_api/Invoice/query_invoice");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("taxNo", taxNo);
        params.addBodyParameter("page_size", 10);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    taclistCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                           count= jsonObjec.optInt("count", 0);
                           page_count= jsonObjec.optInt("page_count", 0);
                           page_index= jsonObjec.optInt("page_index", 0);
                        Log.e(TAG, "count:"+count+"  page_count:"+page_count+"  page_index:"+page_index );
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String id = value.getString("id");
                        String uid = value.getString("uid");
                        String taxAmount = value.getString("taxAmount");
                        String ctime = value.getString("ctime");
                        String check_res = value.getString("check_res");
                        mTaxListBean = new TaxListBean(id,uid,taxAmount,ctime,check_res);
                        ListBean.add(mTaxListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (taclistCode == 200) {
                    mTaxListbeanAdapter = new TaxListbeanAdapter(getBaseContext().getApplicationContext(),ListBean);
                    mTaxListbeanAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mTaxListbeanAdapter);

                }
                if (taclistCode == 201) {


                }
                if (taclistCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {

            }
        });

    }





//    private void filterData(String filterStr) {
//       // List<TaxListBean> SortList = new ArrayList<TaxListBean>();
//             //ListBean.clear();
//
//
//           // ListBean.clear();
//            for (TaxListBean sortModel : ListBean) {
//                String name = sortModel.getCtime();
//                if (filterStr.equals(stampToDate(name)) ) {
//                    ListBean.add(sortModel);
//                    mTaxListbeanAdapter = new TaxListbeanAdapter(getBaseContext().getApplicationContext(),ListBean);
//                    mTaxListbeanAdapter.notifyDataSetChanged();
//                    mListView.setAdapter(mTaxListbeanAdapter);
//                }else{
//                    ListBean.remove(sortModel);
//                }
//            }
//
//        mTaxListbeanAdapter.updateListView(ListBean);
//    }

    private final OnDateSetListener mOnDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DateScrollerDialog timePickerView, long milliseconds) {
            mLastTime = milliseconds;
            myTime = getDateToString(milliseconds);
           // showTime.setText(myTime);
            myTime=myTime.substring(0,7);
            Log.e(TAG, "text"+myTime);
           // filterData(text);
//            for (int i = 0; i<ListBean.size(); i++) {
//                Log.e(TAG, "i"+i);
//                View view=mListView.getChildAt(i);
//                TextView mTextView=view.findViewById(R.id.list_time);
//                String string=mTextView.getText().toString();
//                if(string.equals(text)){
//                    TextView list_moen=view.findViewById(R.id.list_moeny);
//                    String list_moeny=list_moen.getText().toString();
//                    TextView list_check_re=view.findViewById(R.id.list_check_res);
//                    String list_check_res=list_check_re.getText().toString();
//                    Log.e(TAG, "list_moeny"+list_moeny);
//                    Log.e(TAG, "string"+string);
//                    Log.e(TAG, "list_check_res"+list_check_res);
//
//                 }else{
//
//                }
//            }
        }
    };




    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(Long.parseLong(s+"000"));
        res = simpleDateFormat.format(date);
        return res;
    }
    private void shoewtime() {
        DateScrollerDialog dialog = new DateScrollerDialog.Builder()
                .setType(Type.YEAR_MONTH)
                .setMinMilliseconds(System.currentTimeMillis() - HUNDRED_YEARS)
                .setMaxMilliseconds(System.currentTimeMillis())
                .setCurMilliseconds(mLastTime)
                .setCallback(mOnDateSetListener)
                .build();


        if (dialog != null) {
            if (!dialog.isAdded()) {
                dialog.show(getFragmentManager(), "year_month_day");
            }
        }


    }
    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }
}
